{% extends "base.html" %}

{% block title %}后台管理 - 云水禅心居{% endblock %}

{% block extra_head %}
<style>
    .admin-container {
        max-width: 1200px;
        margin: 2rem auto;
        padding: 1rem;
    }
    
    .admin-section {
        background-color: var(--card-bg);
        border-radius: 10px;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
    }
    
    .admin-section:hover {
        box-shadow: 0 5px 15px rgba(0,0,0,0.15);
        transform: translateY(-3px);
    }
    
    .admin-title {
        font-size: 1.5rem;
        margin-bottom: 1.5rem;
        color: var(--primary-color);
        border-bottom: 2px solid var(--accent-color);
        padding-bottom: 0.5rem;
        transition: color var(--transition-time);
    }
    
    .admin-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 1rem;
    }
    
    .admin-table th, .admin-table td {
        padding: 0.8rem;
        text-align: left;
        border-bottom: 1px solid var(--border-color);
        transition: border-color var(--transition-time);
    }
    
    .admin-table th {
        background-color: rgba(var(--primary-color-rgb), 0.1);
        font-weight: bold;
        color: var(--primary-color);
        transition: background-color var(--transition-time), color var(--transition-time);
    }
    
    .admin-table tr:hover {
        background-color: rgba(var(--primary-color-rgb), 0.05);
    }
    
    .btn-delete-admin {
        background-color: #dc3545;
        color: white;
        border: none;
        padding: 0.3rem 0.8rem;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s ease, transform 0.2s ease;
    }
    
    .btn-delete-admin:hover {
        background-color: #c82333;
        transform: scale(1.05);
    }
    
    .user-actions, .post-actions {
        display: flex;
        gap: 0.5rem;
    }
    
    .empty-message {
        color: var(--secondary-color);
        text-align: center;
        padding: 1rem;
        font-style: italic;
    }
    
    /* 确认对话框样式 */
    .confirm-dialog {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
        z-index: 1000;
        justify-content: center;
        align-items: center;
    }
    
    .dialog-content {
        background-color: var(--card-bg);
        padding: 2rem;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        max-width: 400px;
        width: 90%;
        text-align: center;
        transition: background-color var(--transition-time);
    }
    
    .dialog-title {
        font-size: 1.3rem;
        margin-bottom: 1rem;
        color: var(--primary-color);
        transition: color var(--transition-time);
    }
    
    .dialog-buttons {
        display: flex;
        justify-content: center;
        gap: 1rem;
        margin-top: 1.5rem;
    }
    
    .btn-confirm, .btn-cancel {
        padding: 0.5rem 1.5rem;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-weight: bold;
        transition: background-color 0.3s ease, transform 0.2s ease;
    }
    
    .btn-confirm {
        background-color: #dc3545;
        color: white;
    }
    
    .btn-cancel {
        background-color: #6c757d;
        color: white;
    }
    
    .btn-confirm:hover, .btn-cancel:hover {
        transform: scale(1.05);
    }
    
    .btn-confirm:hover {
        background-color: #c82333;
    }
    
    .btn-cancel:hover {
        background-color: #5a6268;
    }
    
    /* 文章标题超出部分省略 */
    .post-title {
        max-width: 300px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    /* 标签样式 */
    .post-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 0.3rem;
    }
    
    .tag {
        font-size: 0.75rem;
        background-color: var(--accent-color);
        color: white;
        padding: 0.1rem 0.4rem;
        border-radius: 3px;
        display: inline-block;
    }
    
    /* 服务器状态模块样式 */
    .server-status {
        margin-bottom: 1rem;
    }
    
    .status-item {
        margin-bottom: 1rem;
    }
    
    .status-label {
        font-weight: bold;
        margin-bottom: 0.3rem;
        color: var(--primary-color);
    }
    
    .status-bar-container {
        width: 100%;
        height: 25px;
        background-color: #f5f5f5;
        border-radius: 5px;
        overflow: hidden;
        transition: all 0.3s ease;
    }
    
    .status-bar {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding-right: 10px;
        background: linear-gradient(90deg, #4caf50, #8bc34a);
        color: white;
        font-weight: bold;
        transition: all 0.5s ease;
    }
    
    /* 高使用率时的警告颜色 */
    .status-bar.warning {
        background: linear-gradient(90deg, #ff9800, #ffc107);
    }
    
    .status-bar.danger {
        background: linear-gradient(90deg, #f44336, #ff5722);
    }
    
    .refresh-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 1rem;
    }
    
    .btn-refresh {
        background-color: var(--primary-color);
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }
    
    .btn-refresh:hover {
        background-color: var(--accent-color);
    }
    
    #last-update {
        font-size: 0.9rem;
        color: var(--secondary-color);
    }
    
    /* IP访问信息样式 */
    .ip-paths {
        display: flex;
        flex-wrap: wrap;
        gap: 0.3rem;
        max-height: 100px;
        overflow-y: auto;
    }
    
    .ip-path {
        font-size: 0.75rem;
        background-color: rgba(var(--primary-color-rgb), 0.1);
        color: var(--primary-color);
        padding: 0.1rem 0.4rem;
        border-radius: 3px;
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px;
    }
    
    .user-agent {
        max-width: 200px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    /* 添加状态样式 */
    .status-banned {
        color: #ff4444;
        font-weight: bold;
    }
    
    .status-normal {
        color: #00C851;
    }
</style>
{% endblock %}

{% block content %}
<div class="admin-container">
    <div class="admin-section">
        <h2 class="admin-title">服务器状态</h2>
        <div class="server-status">
            <div class="status-item">
                <div class="status-label">CPU使用率</div>
                <div class="status-bar-container">
                    <div class="status-bar" style="width: {{ cpu_percent }}%;" id="cpu-bar">
                        <span class="status-value">{{ cpu_percent }}%</span>
                    </div>
                </div>
            </div>
            <div class="status-item">
                <div class="status-label">内存使用率</div>
                <div class="status-bar-container">
                    <div class="status-bar" style="width: {{ memory_percent }}%;" id="memory-bar">
                        <span class="status-value">{{ memory_percent }}%</span>
                    </div>
                </div>
            </div>
            <div class="status-item">
                <div class="status-label">磁盘使用率</div>
                <div class="status-bar-container">
                    <div class="status-bar" style="width: {{ disk_percent }}%;" id="disk-bar">
                        <span class="status-value">{{ disk_percent }}%</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="refresh-container">
            <span id="last-update">最后更新: {{ update_time }}</span>
        </div>
    </div>
    
    <div class="admin-section">
        <h2 class="admin-title">用户管理</h2>
        
        {% if users %}
        <table class="admin-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>注册时间</th>
                    <th>文章数</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for user in users %}
                <tr>
                    <td>{{ user.id }}</td>
                    <td>{{ user.username }}</td>
                    <td>{{ user.registered_at.strftime('%Y-%m-%d %H:%M') }}</td>
                    <td>{{ user.posts|length }}</td>
                    <td class="user-actions">
                        {% if user.username != 'admin' %}
                        <button class="btn-delete-admin" onclick="confirmDeleteUser({{ user.id }}, '{{ user.username }}')">删除</button>
                        {% else %}
                        <span>管理员</span>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <p class="empty-message">没有用户数据</p>
        {% endif %}
    </div>
    
    <div class="admin-section">
        <h2 class="admin-title">文章管理</h2>
        
        {% if posts %}
        <table class="admin-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>标题</th>
                    <th>作者</th>
                    <th>发布时间</th>
                    <th>标签</th>
                    <th>评分</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for post in posts %}
                <tr>
                    <td>{{ post.id }}</td>
                    <td class="post-title" title="{{ post.title }}">
                        <a href="{{ url_for('post', post_id=post.id) }}" target="_blank">{{ post.title }}</a>
                    </td>
                    <td>{{ post.author.username }}</td>
                    <td>{{ post.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
                    <td>
                        <div class="post-tags">
                            {% for tag in post.tags %}
                            <span class="tag">{{ tag.name }}</span>
                            {% endfor %}
                        </div>
                    </td>
                    <td>{{ post.average_rating }} ({{ post.rating_count }})</td>
                    <td class="post-actions">
                        <button class="btn-delete-admin" onclick="confirmDeletePost({{ post.id }}, '{{ post.title }}')">删除</button>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <p class="empty-message">没有文章数据</p>
        {% endif %}
    </div>
    
    <div class="admin-section">
        <h2 class="admin-title">IP访问信息</h2>
        <div class="refresh-container">
            <button class="btn-refresh" id="refresh-ip-btn">整理IP访问信息</button>
            <span id="ip-last-update">最后更新: 未加载</span>
        </div>
        <div id="ip-visits-container">
            <p class="empty-message">点击"整理IP访问信息"按钮加载数据</p>
        </div>
    </div>
</div>

<!-- 删除用户确认对话框 -->
<div id="deleteUserDialog" class="confirm-dialog">
    <div class="dialog-content">
        <h3 class="dialog-title">确认删除用户</h3>
        <p>您确定要删除用户 <span id="deleteUserName"></span> 吗？</p>
        <p>这将同时删除该用户的所有文章和评分！</p>
        <div class="dialog-buttons">
            <form id="deleteUserForm" method="POST" action="">
                <button type="submit" class="btn-confirm">确认删除</button>
            </form>
            <button class="btn-cancel" onclick="closeDialog('deleteUserDialog')">取消</button>
        </div>
    </div>
</div>

<!-- 删除文章确认对话框 -->
<div id="deletePostDialog" class="confirm-dialog">
    <div class="dialog-content">
        <h3 class="dialog-title">确认删除文章</h3>
        <p>您确定要删除文章 <span id="deletePostTitle"></span> 吗？</p>
        <div class="dialog-buttons">
            <form id="deletePostForm" method="POST" action="">
                <button type="submit" class="btn-confirm">确认删除</button>
            </form>
            <button class="btn-cancel" onclick="closeDialog('deletePostDialog')">取消</button>
        </div>
    </div>
</div>

<script>
    // 确认删除用户
    function confirmDeleteUser(userId, username) {
        document.getElementById('deleteUserName').textContent = username;
        document.getElementById('deleteUserForm').action = "/admin/delete_user/" + userId;
        showDialog('deleteUserDialog');
    }
    
    // 确认删除文章
    function confirmDeletePost(postId, title) {
        document.getElementById('deletePostTitle').textContent = title;
        document.getElementById('deletePostForm').action = "/admin/delete_post/" + postId;
        showDialog('deletePostDialog');
    }
    
    // 显示对话框
    function showDialog(dialogId) {
        document.getElementById(dialogId).style.display = 'flex';
    }
    
    // 关闭对话框
    function closeDialog(dialogId) {
        document.getElementById(dialogId).style.display = 'none';
    }
    
    // 点击对话框外部关闭
    window.onclick = function(event) {
        if (event.target.className === 'confirm-dialog') {
            event.target.style.display = "none";
        }
    }
    
    // 根据使用率添加警告颜色
    function updateStatusBarColors() {
        const cpuBar = document.getElementById('cpu-bar');
        const memoryBar = document.getElementById('memory-bar');
        const diskBar = document.getElementById('disk-bar');
        
        const bars = [cpuBar, memoryBar, diskBar];
        
        bars.forEach(bar => {
            const value = parseFloat(bar.style.width);
            if (value >= 90) {
                bar.classList.add('danger');
                bar.classList.remove('warning');
            } else if (value >= 70) {
                bar.classList.add('warning');
                bar.classList.remove('danger');
            } else {
                bar.classList.remove('warning', 'danger');
            }
        });
    }
    
    // 刷新统计数据函数
    function refreshStats() {
        fetch('/admin/refresh_stats')
            .then(response => response.json())
            .then(data => {
                document.getElementById('cpu-bar').style.width = data.cpu_percent + '%';
                document.getElementById('cpu-bar').querySelector('.status-value').textContent = data.cpu_percent + '%';
                
                document.getElementById('memory-bar').style.width = data.memory_percent + '%';
                document.getElementById('memory-bar').querySelector('.status-value').textContent = data.memory_percent + '%';
                
                document.getElementById('disk-bar').style.width = data.disk_percent + '%';
                document.getElementById('disk-bar').querySelector('.status-value').textContent = data.disk_percent + '%';
                
                document.getElementById('last-update').textContent = '最后更新: ' + data.update_time;
                
                updateStatusBarColors();
            })
            .catch(error => {
                console.error('刷新统计数据失败:', error);
            });
    }
    
    // 页面加载时更新状态栏颜色
    document.addEventListener('DOMContentLoaded', function() {
        updateStatusBarColors();
        
        // 启动自动刷新计时器（每5秒刷新一次）
        setInterval(refreshStats, 5000);
        
        // 添加IP访问信息刷新按钮事件
        document.getElementById('refresh-ip-btn').addEventListener('click', refreshIpVisits);
    });
    
    // 刷新IP访问信息
    function refreshIpVisits() {
        fetch('/admin/ip_visits')
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    document.getElementById('ip-visits-container').innerHTML = 
                        `<p class="empty-message">${data.error}</p>`;
                    return;
                }
                
                // 更新最后更新时间
                document.getElementById('ip-last-update').textContent = '最后更新: ' + data.update_time;
                
                // 如果没有IP访问信息
                if (data.ip_visits.length === 0) {
                    document.getElementById('ip-visits-container').innerHTML = 
                        '<p class="empty-message">没有IP访问信息</p>';
                    return;
                }
                
                // 创建IP访问信息表格
                let html = `
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>IP地址</th>
                            <th>地理位置</th>
                            <th>访问次数</th>
                            <th>最后访问时间</th>
                            <th>访问路径</th>
                            <th>浏览器信息</th>
                            <th>状态</th>
                        </tr>
                    </thead>
                    <tbody>
                `;
                
                // 添加每一行IP访问信息
                data.ip_visits.forEach(ip => {
                    const statusClass = ip.is_banned ? 'status-banned' : 'status-normal';
                    const statusText = ip.is_banned ? `封禁中 (解封时间: ${ip.unban_time})` : '正常';
                    
                    html += `
                    <tr>
                        <td>${ip.ip}</td>
                        <td>${ip.location}</td>
                        <td>${ip.count}</td>
                        <td>${ip.last_visit}</td>
                        <td>
                            <div class="ip-paths">
                                ${ip.paths.map(path => `<span class="ip-path">${path}</span>`).join('')}
                            </div>
                        </td>
                        <td class="user-agent" title="${ip.user_agent}">${ip.user_agent.substring(0, 30)}${ip.user_agent.length > 30 ? '...' : ''}</td>
                        <td class="${statusClass}">${statusText}</td>
                    </tr>
                    `;
                });
                
                html += `
                    </tbody>
                </table>
                `;
                
                // 更新容器内容
                document.getElementById('ip-visits-container').innerHTML = html;
            })
            .catch(error => {
                console.error('获取IP访问信息失败:', error);
                document.getElementById('ip-visits-container').innerHTML = 
                    '<p class="empty-message">获取IP访问信息失败</p>';
            });
    }
</script>
{% endblock %} 